package src

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "regexp"
    _ "regexp"
    "strings"
)

type Util struct {
    Compiled *regexp.Regexp
}

func NewUtil() *Util {
    compile, err := regexp.Compile(`^(?:[a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$`)
    if err != nil {
        log.Fatalf("正则表达式编译失败: %v", err)
        return nil
    }
    return &Util{Compiled: compile}
}

func (u *Util) GetEnv(key1 string, key2 string) string {
    res := os.Getenv(key1)
    if res == "" {
        res = os.Getenv(key2)
    }
    return res
}

func (u *Util) SplitDomainName(domainName string) (string, string) {
    // 将abc.example.com 分解成abc和example.com
    // abc.example.com -> example.com
    // 使用正则表达式检查是否为合法域名
    matchString := u.Compiled.MatchString(domainName)
    if !matchString {
        log.Fatalf("域名不合法: %s", domainName)
        return "", ""
    }

    domainNameArr := strings.Split(domainName, ".")
    if len(domainNameArr) > 2 {
        return strings.Join(domainNameArr[:len(domainNameArr)-2], "."), strings.Join(domainNameArr[len(domainNameArr)-2:], ".")
    } else if len(domainNameArr) == 2 {
        return "@", domainName
    } else {
        return "", domainName
    }
    return "", ""
}

func (u *Util) GetOutsideIpStr() (outsideIp string, err error) {
    response, err := http.Get("http://ident.me")
    if err != nil {
        fmt.Println(err.Error())
        return "", err
    }
    defer response.Body.Close()

    all, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err.Error())
        return "", err
    }
    return string(all), nil
}
